﻿#include "devicechartstab.h"
#include <ui_devicechartstab.h>
#include <QPen>
#include <QLegendMarker>
#include <QDateTime>
#include <QTableWidget>
#include <QHeaderView>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTimer>
#include <QDebug>
#include "Template/singleton.h"

#if _MSC_VER >= 1600
#pragma execution_character_set("utf-8")
#endif


DeviceChartsTSC::DeviceChartsTSC(QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::DeviceChartsTSC)
    , m_start_rotate(new QPushButton())
    , timerHeart(new QTimer(this))
    , confirmDevice(ConfirmDeviceInstance)
    , deviceConfigTab(DeviceConfigTabInstance)
{
    connect(timerHeart, &QTimer::timeout, this, [=]() {confirmDevice->serial_T.write(QByteArray::fromHex("EB901400000000000000000000000000000000")); });
    connect(confirmDevice, &ConfirmDevice::sendSampleRotateTSC, this, &DeviceChartsTSC::setOnceSampleDataChart);

    connect(deviceConfigTab, &DeviceConfigTab::sendIsEnableRotateButton, this, &DeviceChartsTSC::setIsEnableRotateButton);

    ui->setupUi(this);
    set_Bottom_Charts_back();
}

DeviceChartsTSC::~DeviceChartsTSC()
{
    delete ui;
}
void DeviceChartsTSC::set_Bottom_Charts_back()
{
    setFeatures(QDockWidget::DockWidgetMovable);
    setAllowedAreas(Qt::BottomDockWidgetArea);
    setWindowTitle(tr("T_SC"));
    QPen dpen;
    dpen.setWidth(2);
    dpen.setColor(QColor(252, 167, 54));
    m_chart = new QChart;

    m_dseries_Temperature = new QLineSeries;
    m_dseries_Temperature->setPen(dpen);
    //  m_dseries_Temperature->setColor(QColor(252, 167, 54));
    m_dseries_Temperature->setName("温度");  // 设置图例名字

    m_scatterSeries_T = new QScatterSeries();
    m_scatterSeries_T->setMarkerSize(8);
    m_scatterSeries_T->setColor(QColor(252, 167, 54));
    m_scatterSeries_T->setPointsVisible(true);

    //    m_chart->setTitle("坐标图");
    m_chart->addSeries(m_dseries_Temperature);
    m_chart->addSeries(m_scatterSeries_T);

    QFont font_cutline;
    font_cutline.setFamily("微软雅黑");
    font_cutline.setPointSize(8);
    font_cutline.setBold(true);

    m_chart->legend()->markers().at(1)->setVisible(false);
    m_chart->legend()->setFont(QFont("Microsoft YaHei", 10, 70));

    // 设置X 轴坐标
    m_Time_daxisX = new QDateTimeAxis();
    m_Time_daxisX->colorChanged(QColor(32, 159, 223));
    m_Time_daxisX->setTitleText("Time");
    m_Time_daxisX->setTickCount(5);                // 设置X轴坐标网格数
    m_Time_daxisX->setFormat("h:mm:ss");
    m_Time_daxisX->setLabelsFont(QFont("Microsoft YaHei", 10, 70));

    QDateTime xMin, xMax;  // 设置时间坐标轴范围
    xMin = QDateTime::currentDateTime();
    xMax = xMin.addSecs(20);
    m_Time_daxisX->setRange(xMin, xMax);

    // 设置 Y 轴坐标
    daxisY_Temperature = new QValueAxis;
    QFont font_y_Temperature;
    font_y_Temperature.setFamily(QString("Microsoft YaHei"));
    font_y_Temperature.setPointSize(8);
    font_y_Temperature.setBold(true);
    daxisY_Temperature->setLabelsFont(font_y_Temperature);
    daxisY_Temperature->setTitleText("Temperature(°C)");
    daxisY_Temperature->setTitleBrush(QColor(252, 167, 54));
    daxisY_Temperature->setRange(0, 10);
    daxisY_Temperature->setTickCount(5); // 设置Y轴坐标网格数
    daxisY_Temperature->setLabelFormat("%.4f");
    daxisY_Temperature->setLinePenColor(QColor(252, 167, 54));
    daxisY_Temperature->setLabelsColor(QColor(252, 167, 54));

    m_chart->addAxis(m_Time_daxisX, Qt::AlignBottom);
    m_chart->addAxis(daxisY_Temperature, Qt::AlignLeft);

    m_dseries_Temperature->attachAxis(m_Time_daxisX);
    m_dseries_Temperature->attachAxis(daxisY_Temperature);

    m_scatterSeries_T->attachAxis(m_Time_daxisX);
    m_scatterSeries_T->attachAxis(daxisY_Temperature);

    dchartView = new QChartView(m_chart, this);
    dchartView->setRenderHint(QPainter::Antialiasing);

    m_Bottom_TableWidget = new QTableWidget();
    // 设置列数
    m_Bottom_TableWidget->setColumnCount(3);
    // 设置行数
    m_Bottom_TableWidget->setRowCount(1);
    // 设置垂直表头不可见
    m_Bottom_TableWidget->verticalHeader()->setVisible(false);
    // 表头标题用QStringList来表示
    QStringList headerTest;
    //headerTest<<QStringLiteral("数值")<<QStringLiteral("最新取样值")<<QStringLiteral("单位");
    headerTest << "功能" << "最新取样值" << "单位";
    m_Bottom_TableWidget->setHorizontalHeaderLabels(headerTest);
    m_Bottom_TableWidget->horizontalHeader()->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Bottom_TableWidget->setEditTriggers(QTableWidget::NoEditTriggers);
    // 设置整行选中模式
    m_Bottom_TableWidget->setSelectionBehavior(QTableWidget::SelectRows);
    // 设置单选模式
    m_Bottom_TableWidget->setSelectionMode(QTableWidget::SingleSelection);
    // 设置最后一行自适应长度
    m_Bottom_TableWidget->horizontalHeader()->setStretchLastSection(true);

    QTableWidgetItem* item_Unit_Tem_Fun = new QTableWidgetItem("温度");
    item_Unit_Tem_Fun->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    item_Unit_Tem_Fun->setForeground(QColor(252, 167, 54));
    item_Unit_Tem_Fun->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Bottom_TableWidget->setItem(0, 0, item_Unit_Tem_Fun);

    QTableWidgetItem* item_Unit_Tem = new QTableWidgetItem("°C");
    item_Unit_Tem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    item_Unit_Tem->setForeground(QColor(252, 167, 54));
    item_Unit_Tem->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Bottom_TableWidget->setItem(0, 2, item_Unit_Tem);

    m_Label_Sample_Count = new QLabel();
    m_Label_Sample_Count->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Label_Sample_Count->setText(QString("Sample #:%1(captured)").arg(m_Sanple_count));

    m_Sample_Time = new QLabel();
    m_Sample_Time->setFont(QFont("Microsoft YaHei", 10, 70));
    m_Sample_Time->setText(QString("Time: %1").arg(" "));

    m_start_rotate->setFont(QFont("Microsoft YaHei", 10, 70));
    m_start_rotate->setText(tr("开启轮询"));
    m_start_rotate->setFixedSize(80, 30);

    // 垂直布局 上下结构
    m_vLayout = new QVBoxLayout();
    m_vLayout->addWidget(m_start_rotate);
    //m_vLayout->addWidget(m_Label_Sample_Save_Location);
    m_vLayout->addWidget(m_Label_Sample_Count);
    m_vLayout->addWidget(m_Sample_Time);
    m_vLayout->addWidget(m_Bottom_TableWidget);
    m_vLayout->setDirection(QBoxLayout::TopToBottom);

    m_Right_Bottom = new QWidget();
    m_Right_Bottom->setLayout(m_vLayout);

    m_hLayout = new QHBoxLayout();
    // m_hLayout->addWidget(dchartView);
    m_hLayout->addWidget(dchartView);
    m_hLayout->addWidget(m_Right_Bottom);
    m_hLayout->setDirection(QBoxLayout::LeftToRight);
    // 比例
    m_hLayout->setStretchFactor(dchartView, 5);
    m_hLayout->setStretchFactor(m_Right_Bottom, 1);
    //ui->dockWidget_3->setWidget(dchartView);
    //ui->dockWidgetContents->setLayout(m_hLayout);
    QWidget* widget = new QWidget(this);
    widget->setLayout(m_hLayout);
    //this->layout()->addWidget(widget);
    //ui->dockWidgetContents->layout()->addWidget(widget);

    setWidget(widget);
    // 开启循环
    connect(m_start_rotate, &QPushButton::clicked, this, [=]() {
        if (startSampleFlag)
        {
            startSampleFlag = false;
            timerHeart->start(1000);
            m_start_rotate->setText(tr("关闭轮询"));
            // 关闭时钟
            deviceConfigTab->m_timer_TSC->stop();
            // 关闭其他按钮
            connect(this, &DeviceChartsTSC::sendSampleEnable, deviceConfigTab, &DeviceConfigTab::recvSampleEnableStatus);
            emit sendSampleEnable(false);
        }
        else
        {
            startSampleFlag = true;
            timerHeart->stop();
            m_start_rotate->setText(tr("开启轮询"));
            // 开启时钟
            deviceConfigTab->m_timer_TSC->start();
            // 开启其他按钮
            emit sendSampleEnable(true);
        }

        });
}

void DeviceChartsTSC::setIsEnableRotateButton(bool flag)
{
    m_start_rotate->setEnabled(flag);
}

void DeviceChartsTSC::recvComPullOut(QString& portName)
{
    m_start_rotate->setEnabled(false);
}


void DeviceChartsTSC::setOnceSampleDataChart(QByteArray data)
{
	auto iTemperature = data.mid(12, 6).toInt(nullptr, 16);
	double dN = log(pow(2, 24) / iTemperature - 1);
	double dTemperature = 1 / (deviceConfigTab->m_TSC[0] + deviceConfigTab->m_TSC[1] * dN + deviceConfigTab->m_TSC[2] * pow(dN, 2) + deviceConfigTab->m_TSC[3] * pow(dN, 3)) - 273.15;
	if (dTemperature > -100 && dTemperature < 150)
	{
		if (m_bFirstSampling)
		{
			m_bFirstSampling = false;
			m_dMaxT = m_dMinT = dTemperature;
		}
		m_dMaxT = m_dMaxT < dTemperature ? dTemperature : m_dMaxT;
		m_dMinT = m_dMinT > dTemperature ? dTemperature : m_dMinT;
		daxisY_Temperature->setRange(m_dMinT, m_dMaxT + 0.0009);
	}
	QString currDatetime = QString("20" + data.left(12).insert(10, ':').insert(8, ':').insert(6, ' ').insert(4, '-').insert(2, '-'));
	if (m_currDatetime == currDatetime)
	{
		qDebug() << "哈哈，出错了,注意时间";
		return;
	}
	m_Label_Sample_Count->setFont(QFont("Microsoft YaHei", 10, 70));
	m_Label_Sample_Count->setText(QString("Sample #:%1(captured)").arg(++m_Sanple_count));
	m_Sample_Time->setFont(QFont("Microsoft YaHei", 10, 70));
	m_Sample_Time->setText(QString("Time: %1").arg(currDatetime));
	QDateTime currTime = QDateTime::fromString(currDatetime, "yyyy-MM-dd hh:mm:ss");

	if (m_isFirst_Simple)
	{
		//    再次更新坐标轴
		QDateTime xMin, xMax;  // 设置时间坐标轴范围
		xMin = currTime.toLocalTime();
		xMax = xMin.addSecs(20);
		m_Time_daxisX->setRange(xMin, xMax);
		m_isFirst_Simple = false;
	}
	QFont font_cutline;
	font_cutline.setFamily("微软雅黑");
	font_cutline.setPointSize(8);
	font_cutline.setBold(true);

	QDateTime t(currTime);
	//qDebug()<<"dTemperature:"<<dTemperature;
	m_dseries_Temperature->append(t.toMSecsSinceEpoch(), dTemperature);
	m_scatterSeries_T->append(t.toMSecsSinceEpoch(), dTemperature);
	// 设置表
	m_New_Value_Tem = new QTableWidgetItem(QString::number(dTemperature, 'f', 4));
	m_New_Value_Tem->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
	m_New_Value_Tem->setTextColor(QColor(252, 167, 54));
	m_New_Value_Tem->setFont(QFont("Microsoft YaHei", 10, 70));

	m_Bottom_TableWidget->setItem(0, 1, m_New_Value_Tem);
	if (currTime > m_Time_daxisX->max())
	{
		QDateTime xMin;
		xMin = currTime.addSecs(qint64(-20));
		m_Time_daxisX->setRange(xMin, currTime);
	}
	m_currDatetime = currDatetime;

}

